/* Description of a module for writing command memory
 * to RAM using Hyperterminal and Serial Port interface
 * IMPORTANT: Note that transmition data rate is fixed
 * and should be 57600 bps! =)
 */
   
`define DIVIDER 14'd9999

module com_interface
(
  input wire clk_ext, //external clock
  input wire rst_, //reset
  input wire rd,
  input wire cd,
  input wire dsr,
  input wire cts,
  output wire dtr,
  output wire rts,
  output reg [15:0] data, //data to be written to RAM
  output reg [15:0] addr, //address where to write in RAM
  output reg wr_en //write_enable for RAM
);
/* Assignments for null-moden connection */
assign dsr = dtr;
assign cd = dtr;
assign cts = rts;

reg [13:0] count;
reg [3:0] rd_cnt; // counter for frame timing
reg clk; //internal clock
reg clk_en; //internal clock enable
reg contin; //flag showing if we should continue to remember data

/* Events on reset */
always @(negedge rst_) begin
  count <= 14'b0;
  clk <= 1'b0;
  wr_en <= 1'b0;
  rd_cnt <= 4'b0;
  clk_en <= 1'b0;
end

/* Generation of internal clock */
always @(posedge clk_ext) begin
  count <= (count == `DIVIDER)? 0 : count + 1;
  clk <= (count == `DIVIDER & clk_en)? ~clk :
                              (~clk_en)? 1'b0 : clk;
end

/* Generation of frame timing counter */
always @(posedge clk)
  rd_cnt <= (rd_cnt == 4'd9)? 0 : rd_cnt + 1;
   
always @(negedge rd)
  clk_en <= (rd_cnt == 4'd0)? 1'b1 : clk_en;
always @*
  clk_en <= (rd_cnt == 4'd9)? 1'b0 : clk_en; //magic
/* Filling data register */  
always @(posedge clk) begin
  if(~rd_cnt & rd_cnt != 4'd9 & ~contin)
    data[rd_cnt-1] <= rd;
  else if (~rd_cnt & rd_cnt != 4'd9 & contin)
    data[8+rd_cnt-1] <= rd;
end
  

endmodule